package com.example.service.implService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.config.ResponseVO;
import com.example.mapper.*;
import com.example.pojo.*;
import com.example.pojo.dto.DishRecipeDTO;
import com.example.pojo.dto.DishWithAllergyInfo;
import com.example.service.DishesService;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DishesServiceImpl implements DishesService {
    @Resource
    private DishesInfoMapper dishesInfoMapper;
    @Resource
    private DishesRecipeMapper dishesRecipeMapper;
    @Resource
    private RecipeInfoMapper recipeInfoMapper;
    @Resource
    private RecipeDateMapper recipeDateMapper;
    @Resource
    private HealthInfoMapper healthInfoMapper;
    @Resource
    private StuMapper stuMapper;

    @Override
    public ResponseEntity<ResponseVO<List<DishesInfo>>> selectAllDishes() {
        List<DishesInfo> dishesInfos = dishesInfoMapper.selectList(null);
        if (!dishesInfos.isEmpty()) {
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "菜品信息获取成功", dishesInfos));
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "暂无菜品数据", null));
    }

    @Override
    public IPage<DishesInfo> getDishesByName(int currentPage, int limit, String dishesName) {
        // 创建Page对象
        Page<DishesInfo> page = new Page<>(currentPage, limit);

        // 构建查询条件
        QueryWrapper<DishesInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(dishesName)) {
            queryWrapper.like("dish_name", dishesName);
        }

        // 执行分页查询
        return dishesInfoMapper.selectPage(page, queryWrapper);
    }
    @Override
    public IPage<DishesInfo> getAllDishesPage(int currentPage, int limit) {
        Page<DishesInfo> page = new Page<>(currentPage,limit);
        return dishesInfoMapper.selectPage(page,null);
    }

    @Override
    public int batchDeleteDishesInfo(List<Integer> ids) {
        return dishesInfoMapper.deleteBatchIds(ids);
    }

    @Override
    public ResponseEntity<ResponseVO<String>> addOrUpdateDish(DishesInfo dishesInfo) {
        String msg = "";
        System.out.println(dishesInfo.getDishId());
        if(dishesInfo.getDishId()==0){
            msg = "新增";
            LocalDateTime now = LocalDateTime.now();
            System.out.println(now.getSecond());
            if(now.getSecond()==0){
                now = LocalDateTime.now();
            }
            dishesInfo.setCreatedAt(now);
            int insert = dishesInfoMapper.insert(dishesInfo);
            if(insert>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, msg+"成功"));
            }
        }else {
            msg = "修改";
            int update = dishesInfoMapper.updateById(dishesInfo);
            if(update>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, msg+"成功"));
            }
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST, msg+"失败"));
    }

    @Override
    public ResponseEntity<ResponseVO<String>> deleteDish(Integer dishesInfoId) {
        int i = dishesInfoMapper.deleteById(dishesInfoId);
        if(i>0){
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "删除成功"));
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST, "删除失败"));
    }

    @Override
    public ResponseEntity<ResponseVO<String>> addOrUpdateRecipeInfo(RecipeInfo recipeInfo) {
        String msg = "";
        if(Objects.isNull(recipeInfo.getRecipeId())){
            msg = "新增";
            int insert = recipeInfoMapper.insert(recipeInfo);
            if(insert>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, msg+"成功"));
            }
        }else {
            msg = "修改";
            int update = recipeInfoMapper.updateById(recipeInfo);
            if(update>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, msg+"成功"));
            }
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST, msg+"失败"));
    }

    @Override
    public ResponseEntity<ResponseVO<List<DishesInfo>>> getDishesByRecipeId(Integer recipeId) {
        // 使用 LambdaQueryWrapper 查询 DishesRecipe 表中与 recipeId 相匹配的所有记录
        LambdaQueryWrapper<DishesRecipe> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DishesRecipe::getRecipeId, recipeId);
        List<DishesRecipe> dishesRecipes = dishesRecipeMapper.selectList(queryWrapper);

        // 提取 dish_id 列表
        List<Integer> dishIds = dishesRecipes.stream()
                .map(DishesRecipe::getDishId)
                .collect(Collectors.toList());

        // 如果没有找到任何 dish_id，则直接返回空列表
        if (dishIds.isEmpty()) {
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST, "No dishes found for the given recipeId", Collections.emptyList()));
        }

        // 使用 LambdaQueryWrapper 查询 DishesInfo 表中与 dish_ids 相匹配的所有记录
        LambdaQueryWrapper<DishesInfo> infoQueryWrapper = Wrappers.lambdaQuery();
        infoQueryWrapper
                .in(DishesInfo::getDishId, dishIds)
                .orderByAsc(DishesInfo::getDishType);
        List<DishesInfo> dishesInfos = dishesInfoMapper.selectList(infoQueryWrapper);

        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "Success", dishesInfos));
    }

    @Override
    public ResponseEntity<ResponseVO<List<DishWithAllergyInfo>>> getRecipeByDateOrClassId(String date,Long classId) {
        QueryWrapper<RecipeDate> recipeDateQueryWrapper = new QueryWrapper<>();
        recipeDateQueryWrapper.eq("recipe_date",date);
        // 查询到该日期的所有菜品
        RecipeDate recipeDate = recipeDateMapper.selectOne(recipeDateQueryWrapper);
        if(Objects.isNull(recipeDate)){
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST,"该日期还为设置食谱"));
        }
        // 查询班级内所有学生
        List<StuInfo> stuInfos = stuMapper.selectList(Wrappers.<StuInfo>lambdaQuery().eq(StuInfo::getClassId, classId));
        // 收集所有学生的健康信息ID
        List<Long> healthIds = stuInfos.stream()
                .map(StuInfo::getHealthId)
                .collect(Collectors.toList());
        // 查询所有学生的过敏信息
        List<HealthInfo> healthInfos = healthIds.isEmpty() ? Collections.emptyList() :
                healthInfoMapper.selectBatchIds(healthIds);
        // 获取所有菜品信息
        ResponseEntity<ResponseVO<List<DishesInfo>>> dishesByRecipeId = getDishesByRecipeId(recipeDate.getRecipeId());
        List<DishesInfo> data = dishesByRecipeId.getBody().getData();
        // 构建菜品与过敏信息的映射
        List<DishWithAllergyInfo> dishWithAllergyInfos = new ArrayList<>();
        for (DishesInfo dish : data) {
            DishWithAllergyInfo dishWithAllergyInfo  = new DishWithAllergyInfo();
            BeanUtils.copyProperties(dish, dishWithAllergyInfo);
            dishWithAllergyInfo.setAllergicStudents(getAllergicStudents(dish, healthInfos));
            dishWithAllergyInfos.add(dishWithAllergyInfo);
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK,"获取数据成功",dishWithAllergyInfos));
    }

    @Override
    public ResponseEntity<ResponseVO<List<DishesInfo>>> getRecipeByDate(String date) {
        QueryWrapper<RecipeDate> recipeDateQueryWrapper = new QueryWrapper<>();
        recipeDateQueryWrapper.eq("recipe_date",date);
        RecipeDate recipeDate = recipeDateMapper.selectOne(recipeDateQueryWrapper);
        // 判断该日期是否有设置菜谱
        if(Objects.isNull(recipeDate)){
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST,"暂无数据"));
        }
        return getDishesByRecipeId(recipeDate.getRecipeId());
    }


    @Override
    public ResponseEntity<ResponseVO<String>> addOrUpdateRecipeDate(RecipeDate recipeDate) {
        String msg = "";
        if(Objects.isNull(recipeDate.getRecipeDateId())){
            msg = "新增";
            int insert = recipeDateMapper.insert(recipeDate);
            if(insert>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, msg+"成功"));
            }
        }else {
            msg = "修改";
            int update = recipeDateMapper.updateById(recipeDate);
            if(update>0){
                return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, msg+"成功"));
            }
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST, msg+"失败"));
    }

    @Override
    public ResponseEntity<ResponseVO<List<DishRecipeDTO>>> getDishRecipeDtoList(){
        List<RecipeInfo> recipeInfos = dishesRecipeMapper.selectRecipesWithDishes();

        // 将RecipeInfo转换为DishRecipeDTO，并填充children
        Map<Integer, DishRecipeDTO> dtoMap = new HashMap<>();
        for (RecipeInfo ri : recipeInfos) {
            DishRecipeDTO dto = new DishRecipeDTO();
            BeanUtils.copyProperties(ri, dto);
            dtoMap.put(dto.getRecipeId(), dto);
        }

        // 查询关联的DishesInfo，并填充到相应的DishRecipeDTO.children中
        List<DishesRecipe> dishesRecipes = dishesRecipeMapper.selectList(null); // 假设存在这样一个mapper方法
        for (DishesRecipe dr : dishesRecipes) {
            DishRecipeDTO dto = dtoMap.get(dr.getRecipeId());
            if (dto != null) {
                if (dto.getDishesInfo() == null) {
                    dto.setDishesInfo(new ArrayList<>());
                }
                DishesInfo di = dishesInfoMapper.selectById(dr.getDishId()); // 获取详细的菜品信息
                dto.getDishesInfo().add(di);
            }
        }

        ArrayList<DishRecipeDTO> dishRecipeDTOS = new ArrayList<>(dtoMap.values());
        if(dishRecipeDTOS.isEmpty()){
            return ResponseEntity.ok(new ResponseVO<>(HttpStatus.BAD_REQUEST, "获取失败"));
        }
        return ResponseEntity.ok(new ResponseVO<>(HttpStatus.OK, "获取成功",dishRecipeDTOS));
    }

    private List<String> getAllergicStudents(DishesInfo dish, List<HealthInfo> healthInfos) {
        // 检查dish是否为null
        if (dish == null) {
            throw new IllegalArgumentException("Dish cannot be null");
        }

        // 检查healthInfos是否为null或空
        if (healthInfos == null || healthInfos.isEmpty()) {
            return Collections.emptyList(); // 或者抛出异常，取决于业务逻辑
        }

        List<String> allergicStudents = new ArrayList<>();
        for (HealthInfo healthInfo : healthInfos) {
            if (healthInfo.getFoodAllergy() != null &&
                    Arrays.stream(healthInfo.getFoodAllergy().split(","))
                            .anyMatch(dish.getAllergenInfo()::contains)) {
                allergicStudents.add(stuMapper.selectById(healthInfo.getStuId()).getName()); // 确保 StudentName 方法存在
            }
        }
        return allergicStudents;
    }
}
